/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.wishlist;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.view.CrossableItem;
import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.ReturnItem;
import com.phonebooksharing.dto.gallery.WishlistItem;

@SuppressWarnings("unchecked")
public class WishlistSearchActivity extends ListActivity {
    
    private WishlistListAdapter adapter;
    private View emptyView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.list_layout_with_empty);
        getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
        
        emptyView = findViewById(R.id.empty);
        ((TextView)emptyView.findViewById(android.R.id.text1)).setText(R.string.wishlist_search_no_match);
        
        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            doSearchQuery(queryIntent);
        }
        
        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(adapter.items.get(arg2).item.prodUrl));
                startActivity(i);
            }
        });
    }

    protected ArrayList<CrossableItem> checkList = new ArrayList<CrossableItem>();
    protected View.OnClickListener checkListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iv = (ImageView)v.findViewById(R.id.check);
            CrossableItem vh = (CrossableItem)v.getTag();
            
            if(!vh.isCrossed) {
                iv.setImageState(new int[] { android.R.attr.state_checked }, true);
                iv.setTag("1");
                checkList.add(vh);
                vh.isCrossed = true;
            } else {
                iv.setImageState(new int[] { }, true);
                iv.setTag("0");
                checkList.remove(vh);
                vh.isCrossed = false;
            }
            
            final int s = checkList.size();
            if(s == 1) {//display actions
                showActionPanel();
            } else if (s == 0) {//display actions
                hideActionPanel();
            }
        }
    };
    
    private void hideActionPanel() {
        actionsPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out));
        actionsPanel.setVisibility(View.GONE);

        shown = false;
    }
    
    private View actionsPanel;
    private boolean shown;
    private void showActionPanel() {
        View v = actionsPanel;
        if (shown) return;
        if (v == null) {
//            v = ((View) getParent().getParent()).findViewById(R.id.dash_actions);
            v = ((ViewStub)findViewById(R.id.actionStub)).inflate();
        }
        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in));
        v.setVisibility(View.VISIBLE);
        //setup button archive
        Button b1 = (Button)v.findViewById(android.R.id.button1);
        b1.setText(R.string.wishlist_add);
        b1.setOnClickListener(getButtonListener());
        
        v.findViewById(android.R.id.button2).setVisibility(View.INVISIBLE);
        actionsPanel = v;
        shown = true;
    }
    
    protected OnClickListener getButtonListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InternalManageTask(checkList).execute();
            }
        };
    }
    
    class InternalManageTask extends NetworkHandlerTask<Void, Void, Void> {
        private ArrayList<CrossableItem> checkList;
        public InternalManageTask(ArrayList<CrossableItem> checkList) {
            this.checkList = checkList;
        }
        
        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<CrossableItem> cl = checkList;
            ArrayList<WishlistItem> list = new ArrayList<WishlistItem>();
            WishlistItem igi;
            for (CrossableItem<WishlistItem> ci : cl) {
                igi = ci.item;
                igi.dateGmt = GeneralUtils.getGmtTimeInMilis();
                list.add(igi);
            }
            
            GenericTransferDTO gt = new GenericTransferDTO();
            gt.authItem = Global.authItem;
            gt.items2 = list;
            
            String url = String.format(Global.WISHLIST_SERVLET_URL, "ms" /*ac*/, "awl" /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/);
            try {
                ReturnItem ids = (ReturnItem)doNetworkPost(url, gt);
                if(ids.isOK()) {
                    
                }
                publishProgress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            Toast.makeText(WishlistSearchActivity.this, R.string.wishlist_success_added, Toast.LENGTH_LONG).show();
            finish();
        }
    }
    
    private void doSearchQuery(Intent queryIntent) {
        final String qry = queryIntent.getStringExtra(SearchManager.QUERY);
        new SearchTask(qry).execute();
    }
    
    class SearchTask extends NetworkHandlerTask<Void, ArrayList<CrossableItem<WishlistItem>>, Void> {
        private ProgressDialog d;
        private String qry;

        public SearchTask(String qry) {
            this.qry = qry;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            d = new ProgressDialog(WishlistSearchActivity.this);
            d.setTitle(R.string.wishlist_searching_title);
            d.setMessage(getString(R.string.wishlist_searching_text));
            d.setIndeterminate(true);
            d.setCancelable(true);
            d.show();
        }
        
        @Override
        protected Void doInBackground(Void... params) {
            try {
                ArrayList<CrossableItem<WishlistItem>> items = WishlistSearchHandler.searchProducts(qry);
                publishProgress(items);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            return null;
        }
        
        @Override
        protected void onProgressUpdate(ArrayList<CrossableItem<WishlistItem>>... values) {
            super.onProgressUpdate(values);
            
            adapter = new WishlistListAdapter(WishlistSearchActivity.this, getListView());
            adapter.items = values[0];
            adapter.checkListener = checkListener;
            setListAdapter(adapter);
            getListView().setEmptyView(emptyView);
        }

        @Override
        protected void onPostExecute(Void i) {
            super.onPostExecute(i);

            d.dismiss();
        }
    }
}
